<?php

namespace App\Http\Middleware;

use Closure;
use Log;
use App;

class HttpDiscernMiddleware
{
    protected $controller;
    protected $method;
    protected $api_version;

    /**
     * Request Method&Api Version Discern Middleware
     * @param $request
     * @param Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle($request, Closure $next)
    {
        $real_method = $request->getRealMethod();
        $scheme_host = $request->getSchemeAndHttpHost();
        $request_uri = $request->getRequestUri();
        $client_ip = $request->getClientIp();
        $content_type = $request->getContentType();
        $base_url = $request->getBaseUrl();

        $data = [
            "real_method"=>$real_method,
            "scheme_host"=>$scheme_host,
            "request_uri"=>$request_uri,
            "client_ip"=>$client_ip,
            "content_type"=>$content_type,
            "base_url"=>$base_url,
        ];

        Log::info("Http Request : ".json_encode($data));

        if (strrpos($request_uri,'?')) {
            $temp = explode('?', $request_uri);
            $temp = explode('/', current($temp));
        }else{
            $temp = explode('/', $request_uri);
        }

        $this->controller = $temp[1];
        $this->method = $temp[2];

        try {
            if (strtolower($this->controller)=="api") {
                $this->api_version = $temp[2];
                $this->controller = $temp[3];
                $this->method = $temp[4];
            }

            $tag = ['@method','@api'];
            $request_method = $this->getProperty(
                'App\Http\Controllers\\'.ucwords($this->controller).'Controller',
                $this->method,
                $tag
            );

            Log::info("request_method: ",$request_method);
            if ($request_method['@method'] != strtolower($real_method)) {
                throw new \Exception('方法不支持');
            }

            if (!empty($request_method['@api'])) {
                if (empty($this->api_version)) {
                    throw new \Exception("@api 版本为空");
                }
                $api = (float) explode(':', $request_method['@api'])[1];
                $req_api = (float) explode('v',$this->api_version)[1];

                if ($api != $req_api) {
                    throw new \Exception("@api 版本不正确");
                }
            }

        } catch (\Exception $e) {
            throw $e;
        }

        return $next($request);
    }

    /**
     * Get Class Property Function
     * @param $class
     * @param $method
     * @param $tags
     * @return array|null
     * @throws \Exception
     */
    public function getProperty($class, $method, $tags)
    {
        try {
            $req_property = null;
            if (empty($tags)) {
                throw new \Exception('Tag 不能空');
            }
            $controller = new \ReflectionClass($class);
            $method = $controller->getMethod($method);
            $doc = $method->getDocComment();
            $matches = array();
            $req_property = array();
            foreach ($tags as $item) {
                preg_match("/".$item."(.*)(\\r\\n|\\r|\\n)/U", $doc, $matches);
                if (isset($matches[1])) {
                    $req_property[$item]  =trim($matches[1]) ;
                }
            }
            if (!isset($req_property['@method'])) {
                throw new \Exception('请设置@method 属性[必填]');
            }
            return $req_property;

        } catch (\Exception $e) {
            throw $e;
        }
    }
}
